package com.dg.tools

import java.awt.image.BufferedImage

import javax.imageio.ImageIO

import org.imgscalr.Scalr

class ImageUtility {

	static def getImage(String aAbsoluteImagePath, int aWidth) {		
		def imagePath = aAbsoluteImagePath
		
		int lastIndex = imagePath.lastIndexOf(".")
		String fileExtension = imagePath.substring(lastIndex + 1)
		
		def file = new File(imagePath)
		def imagePixelData 
		
		if (aWidth > 0) {
			BufferedImage resizedImage = Scalr.resize(ImageIO.read(file), aWidth);
			
			ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
			ImageIO.write( resizedImage, fileExtension, outputStream );
			outputStream.flush();
			imagePixelData = outputStream.toByteArray();
			outputStream.close();
		} else {
			imagePixelData = file?.bytes
		}
		
		def image = new ImageDataHolder()
		
		image.setImageType(fileExtension)
		image.setImagePixelData(imagePixelData)
		
		return image
	}
	
	static def getImage(String aImagePath) {
		getImage(aImagePath, -1)
	}
}
